/*
 * @Author: sz
 * @Date: 2023-10-26 09:16:15
 * @LastEditors: sz
 * @LastEditTime: 2023-11-15 17:25:03
 * @Description: axios 拦截器
 */
import stores from '../store'
import { removeAuthorization, checkAuthorization } from '@/utils/request'

const resCommon = {
  onFulfilled(response, options) {
    const { message, router } = options
    if (response.status === 200 && response.data.code == 1) {
      return Promise.resolve(response.data)
    }

    if (response.status === 200 && response.data.code == -403) {
      removeAuthorization()
      message.error('登录已过期,请重新登录')
      router.replace('/login')
    }
    return Promise.reject({ ...response }, options)
  },
  onRejected(error, options) {
    const { response } = error
    return Promise.reject(response.data)
  }
}

const reqCommon = {
  /**
   * 发送请求之前做些什么
   * @param config axios config
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {*}
   */
  onFulfilled(config, options) {
    const { message, router, store } = options
    const { url, headers, data, params, method } = config
    var jwts = localStorage.getItem(process.env.VUE_APP_JWT_KEY ? process.env.VUE_APP_JWT_KEY : 'XMJWT')
    if (url.indexOf('login') === -1 && !checkAuthorization()) {
      message.warning('认证 token 已过期，请重新登录', 1, () => {
        router.replace({ path: '/login' })
      })
    }
    if (jwts) {
      headers['Authorization'] = jwts
    }

    Object.assign(headers, { Authorization: store.state.account.jwt })
    return config
  },
  /**
   * 请求出错时做点什么
   * @param error 错误对象
   * @param options 应用配置 包含: {router, i18n, store, message}
   * @returns {Promise<never>}
   */
  onRejected(error, options) {
    const { message } = options
    console.log(stores.getters.account)
    message.error(error.message)
    return Promise.reject(error)
  }
}

export default {
  request: [reqCommon], // 请求拦截
  response: [resCommon] // 响应拦截
}
